import React, { useState, useEffect } from 'react';
import { Input, InputNumber, Tooltip } from 'antd';
import { convertCurrency } from '@/utils/utils'
import './index.less';


interface NumericInputProps {
  style: React.CSSProperties;
  placeholder?: string;
  value?: string;
  onChange?: (value: string) => void;
}

const formatNumber = (value: number) => new Intl.NumberFormat().format(value);

const NumericInput: React.FC<NumericInputProps> = (props) => {
  const { value, placeholder, onChange } = props;

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value: inputValue } = e.target;
    const reg = /^-?\d*(\.\d{0,2})?$/;
    console.log(reg.test(inputValue),'reg.test(inputValue)');
    
    if (reg.test(inputValue) || inputValue === '' || inputValue === '-') {
      if (onChange) {
        onChange(inputValue);
      }
    }
  };

  // '.' at the end or only '-' in the input box.
  const handleBlur = () => {
    let valueTemp = value || '';
    if (value && value.charAt(value.length - 1) === '.' || value === '-') {
      valueTemp = value.slice(0, -1);
    }
    if (onChange) {
      onChange(valueTemp.replace(/0*(\d+)/, '$1'));
    }
  };

  const title = value ? (
    <span className="numeric-input-title">{String(value).slice(0,1)=='-' ? '负'+convertCurrency(String(value).slice(1)) : convertCurrency(value)}</span>
  ) : '';

  return (
    <span>
      <Input
        {...props}
        onChange={handleChange}
        onBlur={handleBlur}
        placeholder={placeholder || ''}
        maxLength={25}
        addonAfter="元"
      />
      {title && <div>{title}</div>}
    </span>
    // <Tooltip trigger={['focus']} title={title} placement="topLeft" overlayClassName="numeric-input">
    //   <Input
    //     {...props}
    //     onChange={handleChange}
    //     onBlur={handleBlur}
    //     placeholder={placeholder || ''}
    //     maxLength={25}
    //   />
    // </Tooltip>
  );
};

export default NumericInput;